<template>
  <section style="height:100%;overflow:auto;">
    <el-tree
      ref="treeRef"
      :data="faultList"
      node-key="id"
      :default-expanded-keys="defaultExpandedKeys"
      :default-checked-keys="dialogData.checkedKeys" 
      :props="defaultProps"
      :show-checkbox="isDialog"
      :check-strictly="isDialog" 
      @node-click="handleNodeClick"
      @check="handelCheckChange">
      <div :class="[!isDialog && 'custom-tree-node', 'dialog-tree-node', currentKey == data.id ? 'select' : '']" slot-scope="{ node, data }">
        <div class="title">
          <!-- 2 解决节点 -->
          <span class="icon" v-if="data.faultLabel && data.relType == 0 || data.dataType == 2">
            {{ data.faultLabel }}
          </span>
          <!-- 1 故障节点 -->
          <span class="icon" v-if="data.relType != 0 && data.dataType == 1">
            {{ getRealTypeName(data.relType) }}
          </span>
          <span @click.stop="isFormDialog? handelCheckChange(data) : openDetail(data)">{{ data.faultDesc }} &nbsp; {{ getComputedStyle(data.relObj || []) }}</span>
        </div>

        
        <div class="btn-parent">
          <!-- 解决方案是叶子节点，不能新建 -->
          <el-dropdown trigger="hover" :show-timeout="150" v-if="!data.libraryId && hasFaultAdd">
            <span class="iconfont icon-add1" @click="handleButtonClick"></span>

            <el-dropdown-menu slot="dropdown">
              <!-- 当该节点下有解决方案，不能新建描述和子描述 -->
              <!-- 第一级（故障对象）不能展示新建描述按钮 -->
              <el-dropdown-item
                v-if="data.faultLevel != 1 && data.dataType === 1"
                class="iconfont icon-btn"
                icon="icon-zhuti"
                @click.native="createDescriptionOrSolution(node.parent.data, 'description')">{{ $t('faultLibrary.createDescriptionBtn') }}
              </el-dropdown-item>

              <el-dropdown-item
                v-if="!data.solutionList || data.solutionList.length === 0"
                class="iconfont icon-btn"
                icon="icon-zizhuti"
                @click.native="createDescriptionOrSolution(data, 'description')">{{ $t('faultLibrary.createSubDescriptionBtn') }}
              </el-dropdown-item>

              <el-dropdown-item
                v-if="!isDialog && (data.faultLevel != 1 && !(data.childrenList || []).find(v => v.dataType === 1))" 
                class="iconfont icon-btn"
                icon="icon-check-circle"
                @click.native="createDescriptionOrSolution(data, 'solution')">{{ $t('faultLibrary.faultObject.createSolution') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-dropdown trigger="click" :show-timeout="150" v-if="(hasFaultEdit || hasFaultDelete) && !isDialog">
            <span class="iconfont icon-MoreOutlined" @click="handleButtonClick"></span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item 
                v-if="hasFaultCopy(data)"
                class="iconfont icon-btn" 
                icon="icon-fuzhi"
                @click.native="copyHandle(data)">{{ $t('common.base.copy') }}
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="hasFaultEdit"
                class="iconfont icon-btn" 
                icon="icon-edit-square1"
                @click.native="editorHandle(data)">{{ $t('common.base.edit') }}
              </el-dropdown-item>
              <el-dropdown-item 
                v-if="hasFaultDelete"
                class="iconfont icon-btn" 
                icon="icon-qingkongshanchu"
                @click.native="deleteHandle(data)">{{ $t('common.base.delete') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </el-tree>
    <!-- 故障对象弹框 -->
    <faultObj 
      v-model="faultObjDialogVisible"
      :current-fault-obj-id='currentFaultObjId'
      @operateSuc="operateSuc"/>

    <!-- 故障描述弹框 -->
    <faultDescription 
      v-model="faultDescriptionDialogVisible" 
      :current-fault-description-id="currentFaultDescriptionId"
      :create-fault-data="createFaultData"
      :isRegister="isRegister"
      @operateSuc="operateSuc"
    />

    <!-- 解决方案弹框 -->
    <FaultSolution 
      v-model="faultSolutionDialogVisible" 
      :current-fault-solution-id="currentFaultSolutionId"
      :create-fault-data="createFaultData"
      :isRegister="isRegister"
      @operateSuc="operateSuc"
    />

    <!-- 复制故障对象弹框 -->
    <FaultCopy
      v-model="faultCopyDialogVisible"
      :current-fault-copy-id="currentFaultCopyId"
      :fault-list="faultList"
      @operateSuc="operateSuc"
    />
  </section>
</template>

<script>
// 故障对象弹框
import FaultObj from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultObj';
// 故障描述弹框
import FaultDescription from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultDescription';
// 解决方案弹框
import FaultSolution from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultSolution';
// 复制故障对象弹框
import FaultCopy from '@src/modules/faultLibrary/components/FaultInformationDialog/FaultCopy';
// api
import { libraryDelete, solutionDelete } from '@src/api/Fault';

import { openAccurateTab } from '@src/util/platform';

import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import AuthUtil from '@src/util/auth';
import { findParents } from '@src/modules/faultLibrary/utils/index';

export default{
  // 故障库tree
  name:'TreeList',
  props: {
    // defaultExpandedKeys: {
    //   type: Array,
    //   default: () => ([])
    // },
    faultList:{
      type:Array,
      default: () => ([])
    },
    initData: {
      type: Object,
      default: () => ({})
    },
    isFormDialog: {
      type: Boolean,
      default: false
    },
    isRegister: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      defaultProps: {
        children:'childrenList',
        label:'faultDesc',

      },

      currentKey:'',

      // 新建/编辑故障对象弹框
      faultObjDialogVisible:false,
      // 当前编辑的故障对象id
      currentFaultObjId:'',
      // 新建/编辑故障描述弹框
      faultDescriptionDialogVisible:false,
      // 当前编辑的故障描述id
      currentFaultDescriptionId:'',
      // 新建/编辑解决方案弹框
      faultSolutionDialogVisible:false,
      // 当前编辑的解决方案id
      currentFaultSolutionId:'',
      // 复制故障对象弹框
      faultCopyDialogVisible: false,
      // 当前复制的故障对象id
      currentFaultCopyId: '',

      // 用于记录新建故障描述和解决方案时一些数据，从列表取得，传给弹框
      createFaultData:{},
      dialogData: {}, // 弹窗内容
      defaultExpandedKeys: []
    }
  },
  computed: {
    auth() {
      return this.initData?.auths || {};
    },
    hasFaultAdd() {
      return AuthUtil.hasAuth(this.auth, 'FAULT_LIBRARY_ADD')
    },
    hasFaultEdit() {
      return AuthUtil.hasAuth(this.auth, 'FAULT_LIBRARY_EDIT')
    },
    hasFaultDelete() {
      return AuthUtil.hasAuth(this.auth, 'FAULT_LIBRARY_DELETE')
    },
    isDialog() {
      return this.dialogData.isDialog || false;
    }
  },
  components:{
    // 新建/编辑故障对象
    FaultObj,
    // 新建/编辑故障描述
    FaultDescription,
    // 新建/编辑解决方案
    FaultSolution,
    // 复制故障对象
    FaultCopy
  },
  mounted() {
    this.setAllExpand(true)
    this.findExpandedNode()
  },

  methods:{
    /** 节点默认展开 */
    setAllExpand(state) {
      var nodes = this.$refs.treeRef.store.nodesMap;
      for (var i in nodes) {
        nodes[i].expanded = state;
      }
    },
    /** 存储展开的数据 */
    findExpandedNode(ids = [], data = this.faultList) { // 寻找所有展开的主节点id
      data.forEach(item => {
        if (this.$refs.treeRef.getNode(item)?.expanded && item.childrenList?.length) {
          ids.push(item.id)
          this.findExpandedNode(ids, item.childrenList)
        }
      })
      this.defaultExpandedKeys = ids;
    },
    handleButtonClick(event) {
      event.stopPropagation();
    },
    handleNodeClick(){
      this.currentKey = this.$refs.treeRef?.getCurrentKey() || ''
    },

    cancelSelect(){
      this.currentKey = this.$refs.treeRef?.setCurrentKey(null)
    },

    getTreeRef(){
      return this.$refs.treeRef
    },


    editorHandle(data = {}){
      // 点击某个具体的菜单后，清空选中状态
      this.cancelSelect();
      const { faultLevel, libraryId, id } = data || {};
      // 第一级是故障对象
      if(faultLevel === 1){
        this.faultObjDialogVisible = true
        this.currentFaultObjId = id;
        return
      }

      // 故障方法
      if(libraryId){
        this.openSolution(id)
        return
      }

      // 故障描述
      this.openDescription(id)
    },

    deleteHandle(item){
      // 点击某个具体的菜单后，清空选中状态
      this.cancelSelect();
      const { libraryId, id } = item || {};
      this.$confirm(this.$t('common.paas.view.designer.workFlow.tip1'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(async () => {
        let res = {}
        if(libraryId){
          // 当前是解决方案
          res = await solutionDelete({solutionId:id})
        }else{
          // 删除故障对象
          res = await libraryDelete({faultId:id})
        }

        if(res.status === 0){
          this.operateSuc();
        }else{
          this.$notify.error({
            title: this.$t('common.base.toast'),
            message: res.message,
            duration: 2000,
          });
        }
      })
    },

    copyHandle(item){
      // 点击某个具体的菜单后，清空选中状态
      this.cancelSelect();
      const { id } = item || {};
      this.openCopy(id);
    },

    setCreateData(parentData = {}, type){
      const { faultLevel } = parentData

      this.createFaultData = {
        parentId:parentData.id,
        faultLevel: faultLevel + 1,
        parentDesc: parentData.faultDesc,
        faultLabel: parentData.faultLabel || this.getRealTypeName(parentData.relType)
      }
    },

    // 新建描述或解决方案
    createDescriptionOrSolution(parentData, type){
      // 点击某个具体的菜单后，清空选中状态
      this.cancelSelect();

      // 新建描述或子描述需要传递当前新建的级别和父节点id给弹框组件，用于提交给接口
      this.setCreateData(parentData, type)
      this.findExpandedNode()

      switch(type){
        case 'description': this.openDescription(); break;
        case 'solution': this.openSolution(); break;
        default: break;
      }
      
    },

    // 打开描述和子描述弹框
    openDescription(id = ''){
      this.faultDescriptionDialogVisible = true;
      this.currentFaultDescriptionId = id;
    },

    // 打开解决方案弹框
    openSolution(id = ''){
      this.faultSolutionDialogVisible = true
      this.currentFaultSolutionId = id;
    },

    // 打开复制弹框
    openCopy(id = ''){
      this.faultCopyDialogVisible = true
      this.currentFaultCopyId = id;
    },

    hasFaultCopy(data) {
      return data.parentId != null || data.dataType === 2;
    },

    operateSuc(){
      this.$emit('getData')
      this.findExpandedNode()
    },

    openDetail(data){
      if(this.isDialog) return;
      const { faultLevel, id, libraryId } = data || {}

      let type = 'description'
      if(faultLevel === 1 ){
        type = 'obj'
      }else if( libraryId ){
        type = 'solution'
      }
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageFaultLibraryDetail,
        key: id,
        params:`type=${type}`,
        fromId
      })
    },
    getRealTypeName(type) {
      return ['', this.$t('common.base.product'), this.$t('common.form.type.material'), this.$t('common.base.sparePart')][type]
    },
    setDialogInfo(data) {
      this.dialogData = data;
    },
    // 单选上级
    handelCheckChange(data) {
      this.$emit('check', data);
    },
    setCheckedKeys() {
      this.$refs.treeRef.setCheckedKeys([]);
    },

    getComputedStyle(arr = []) {
      if (arr.length == 0) return '';
      return '(' + arr.map(v => v.relObjName).join(',') + ')';
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tree{
  .el-tree-node {
    position: relative;
    padding-left: 16px; // 缩进量
  }
  .el-tree-node__children {
    padding-left: 16px; // 缩进量
  }

  // 竖线
  .el-tree-node::before {
    content: "";
    height: 100%;
    width: 1px;
    position: absolute;
    left: 5px;
    top: -26px;
    border-width: 1px;
    border-left: 1px dashed #52627C;
  }
  // 当前层最后一个节点的竖线高度固定
  .el-tree-node:last-child::before {
    height: 45px; // 可以自己调节到合适数值
  }

  // 横线
  .el-tree-node::after {
    content: "";
    width: 20px;
    height: 20px;
    position: absolute;
    left: 5px;
    top: 20px;
    border-width: 1px;
    border-top: 1px dashed #52627C;
  }

  // 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
  & > .el-tree-node::after {
    border-top: none;
  }
  & > .el-tree-node::before {
    border-left: none;
  }
	
  // 展开关闭的icon
  .el-tree-node__expand-icon{
    font-size: 16px;
    // 叶子节点（无子节点）
    &.is-leaf{
      color: transparent;
      // display: none; // 也可以去掉
    }
  }
}

::v-deep .el-tree-node__content{
  border-bottom:1px solid #EBEEF5;
  padding:9px 0;
  height:40px;
  .custom-tree-node.select,&:hover{
    .btn-parent{
      visibility:visible;
      display: flex;
      justify-content: end;
    }
  }
}
.custom-tree-node{
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: calc(100% - 28px);
  .title{
    color:#262626;
    flex:1;
    @include text-ellipsis();
    .icon{
      background: #F4F4F5;
      border: 1px solid #E9E9EB;
      line-height: 20px;
      border-radius: 2px;
      padding: 0px 8px;
      margin-right:8px;
      color: #898989;
      font-size:12px;
    }
  }
}
.el-icon-caret-right{
  margin-left:9px;
}

.btn-parent{
  visibility:hidden;
  padding-right:32px;
  width: 100px;
  .icon-add1,.icon-MoreOutlined{
  
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    padding: 3px 5px;
    color:#595959;
    &:hover{
      background: #F0F2F5;
    }
  }
}

.icon-add1{
  margin-right:8px;
}
// @import '../scss/FaultLibraryView';
::v-deep .icon-btn{
  line-height:32px;
  font-size:14px;
  color:#595959;
  &:hover{
    color:$color-primary-light-6 !important;
  }
  i{
    font-style: normal;
    font-size: 16px;
  }
}

::v-deep .el-tree .el-tree-node__content {
  padding-left: 0 !important;
  .el-tree-node__expand-icon{
    &.expanded.el-icon-caret-right{
      transform: rotate(0deg);
      margin:0 10px;
      &::before {
        content: "\e6d8"; //需要修改的图标e6d9
      }
    }
    &.el-icon-caret-right{
      margin:0 10px;
      &::before{
        content: "\e6d9"; //需要修改的图标
        border: 1px solid rgba(0, 0, 0, 0.1);
      }

      padding: 2px;
      background:#fff;
      height:18px;
      display: flex;
      align-items: center;
      color:rgba(0, 0, 0, 0.7);
      z-index: 1;
    }
    &.is-leaf{
      visibility: hidden;
      // margin-right: -5px;
    }
  }
}


::v-deep {
    .checkTreeClass {
      padding-top: 15px;
      padding-left: 10px;
      // 不可全选样式
      .el-tree-node {
        .is-leaf + .el-checkbox .el-checkbox__inner {
          display: inline-block;
        }
        .el-checkbox .el-checkbox__inner {
          display: none;
        }
      }
    }
}
.dialog-tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: calc(100% - 28px);
  .icon {
    background: #F4F4F5;
    border: 1px solid #E9E9EB;
    line-height: 20px;
    border-radius: 2px;
    padding: 0px 8px;
    margin-right:8px;
    color: #909399;
    font-size:12px;
  }
}
</style>
